package com.tidu.secret.controller;

import com.tidu.secret.service.DocumentSecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 文档处理控制器
 */
@RestController
@RequestMapping("/api/document")
public class DocumentController {
    
    @Autowired
    private DocumentSecurityService documentSecurityService;
    
    /**
     * 识别文档中的敏感内容
     */
    @PostMapping("/identify")
    public ResponseEntity<Map<String, Object>> identifySensitiveContent(
            @RequestParam("file") MultipartFile file,
            @RequestParam("sensitiveWords") String sensitiveWords) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 解析敏感词列表
            List<String> wordList = Arrays.asList(sensitiveWords.split(","));
            
            // 识别敏感内容
            List<DocumentSecurityService.SensitiveContentInfo> results = 
                documentSecurityService.identifySensitiveContent(file, wordList);
            
            response.put("success", true);
            response.put("message", "识别完成");
            response.put("sensitiveContent", results);
            response.put("count", results.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "识别失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 处理文档并返回加密后的文件
     */
    @PostMapping("/process")
    public ResponseEntity<?> processDocument(
            @RequestParam("file") MultipartFile file,
            @RequestParam("sensitiveWords") String sensitiveWords) {
        
        try {
            // 解析敏感词列表
            List<String> wordList = Arrays.asList(sensitiveWords.split(","));
            
            // 处理文档
            byte[] processedDocument = documentSecurityService.processDocument(file, wordList);
            
            // 生成新的文件名
            String originalFileName = file.getOriginalFilename();
            String newFileName = generateProcessedFileName(originalFileName);
            
            // 返回处理后的文件
            ByteArrayResource resource = new ByteArrayResource(processedDocument);
            
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + newFileName + "\"")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .contentLength(processedDocument.length)
                    .body(resource);
                    
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "处理失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
    
    /**
     * 同时识别和处理文档
     */
    @PostMapping("/analyze-and-process")
    public ResponseEntity<Map<String, Object>> analyzeAndProcessDocument(
            @RequestParam("file") MultipartFile file,
            @RequestParam("sensitiveWords") String sensitiveWords) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 解析敏感词列表
            List<String> wordList = Arrays.asList(sensitiveWords.split(","));
            
            // 先识别敏感内容
            List<DocumentSecurityService.SensitiveContentInfo> sensitiveContent = 
                documentSecurityService.identifySensitiveContent(file, wordList);
            
            // 处理文档
            byte[] processedDocument = documentSecurityService.processDocument(file, wordList);
            
            // 生成新的文件名
            String originalFileName = file.getOriginalFilename();
            String newFileName = generateProcessedFileName(originalFileName);
            
            response.put("success", true);
            response.put("message", "分析和处理完成");
            response.put("sensitiveContent", sensitiveContent);
            response.put("sensitiveCount", sensitiveContent.size());
            response.put("processedFileName", newFileName);
            response.put("processedFileSize", processedDocument.length);
            
            // 将处理后的文件内容编码为Base64，便于前端处理
            response.put("processedFileData", java.util.Base64.getEncoder().encodeToString(processedDocument));
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "处理失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 解密文档
     */
    @PostMapping("/decrypt")
    public ResponseEntity<Map<String, Object>> decryptDocument(
            @RequestParam("file") MultipartFile file) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 解密文档
            byte[] decryptedDocument = documentSecurityService.decryptDocument(file);
            
            // 生成新的文件名
            String originalFileName = file.getOriginalFilename();
            String newFileName = generateDecryptedFileName(originalFileName);
            
            response.put("success", true);
            response.put("message", "解密完成");
            response.put("decryptedFileName", newFileName);
            response.put("decryptedFileSize", decryptedDocument.length);
            
            // 将解密后的文件内容编码为Base64，便于前端处理
            response.put("decryptedFileData", java.util.Base64.getEncoder().encodeToString(decryptedDocument));
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "解密失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "ok");
        response.put("message", "文档安全服务运行正常");
        response.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取支持的文件格式
     */
    @GetMapping("/supported-formats")
    public ResponseEntity<Map<String, Object>> getSupportedFormats() {
        Map<String, Object> response = new HashMap<>();
        response.put("formats", Arrays.asList(".doc", ".docx"));
        response.put("maxFileSize", "50MB");
        response.put("description", "支持Microsoft Word文档格式");
        return ResponseEntity.ok(response);
    }
    
    /**
     * 生成处理后的文件名
     */
    private String generateProcessedFileName(String originalFileName) {
        if (originalFileName == null) {
            return "processed_document.docx";
        }
        
        int lastDotIndex = originalFileName.lastIndexOf('.');
        if (lastDotIndex > 0) {
            String nameWithoutExtension = originalFileName.substring(0, lastDotIndex);
            String extension = originalFileName.substring(lastDotIndex);
            return nameWithoutExtension + "_encrypted" + extension;
        } else {
            return originalFileName + "_encrypted";
        }
    }
    
    /**
     * 生成解密后的文件名
     */
    private String generateDecryptedFileName(String originalFileName) {
        if (originalFileName == null) {
            return "decrypted_document.docx";
        }
        
        // 如果文件名包含"_encrypted"，则移除它
        String nameWithoutEncrypted = originalFileName.replace("_encrypted", "");
        
        int lastDotIndex = nameWithoutEncrypted.lastIndexOf('.');
        if (lastDotIndex > 0) {
            String nameWithoutExtension = nameWithoutEncrypted.substring(0, lastDotIndex);
            String extension = nameWithoutEncrypted.substring(lastDotIndex);
            return nameWithoutExtension + "_decrypted" + extension;
        } else {
            return nameWithoutEncrypted + "_decrypted";
        }
    }
}